import Vue from "vue";
import Vuex from "vuex";

import threeParser from "../utils/ThreeParser";
import logParser from "../utils/LogParser";
import eventBus from "../utils/EventBus";
import {
  THREE_CANVAS_DRAW,
  LOG_TO_SCREEN
} from "../utils/EventBus/events";

import {
  COMMIT_COMMAND,
  CHANGE_WS_STATE,
  SET_USERNAME,
  SET_ROOMID,
  SET_OFFLINE
} from "./events";

import {
  sendWsMsg
} from "../utils/WebSocket";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    username: "",
    roomid: "",
    wsState: 0, // WebSocket 连接状态： 0 未开始 1 已连接 2 已返回初始信息
    commands: [],
    offline: false
  },
  mutations: {
    [COMMIT_COMMAND](state, payload) {
      state.commands.push(payload.command);
    },
    [CHANGE_WS_STATE](state, payload) {
      state.wsState = payload.wsState;
    },
    [SET_USERNAME](state, payload) {
      state.username = payload.username;
    },
    [SET_ROOMID](state, payload) {
      state.roomid = payload.roomid;
    },
    [SET_OFFLINE](state, payload) {
      state.offline = payload.offline;
    }
  },
  actions: {
    [COMMIT_COMMAND](context, payload) {
      const command = payload.command;
      if (!payload.onlySend) {
        // 进行本地绘制
        const g = threeParser(command.content);
        if (typeof g === "object") {
          eventBus.$emit(THREE_CANVAS_DRAW, g);
        }
      }
      // 进行解析后再 log
      eventBus.$emit(LOG_TO_SCREEN, logParser(command));
      if (!payload.onlyExecute) {
        // 向服务器提交 command
        sendWsMsg(command);
      }
      // 本地提交
      context.commit(COMMIT_COMMAND, payload);
    },
    [CHANGE_WS_STATE](context, payload) {
      context.commit(CHANGE_WS_STATE, payload);
    },
    [SET_USERNAME](context, payload) {
      window.localStorage.setItem("username", payload.username);
      context.commit(SET_USERNAME, payload);
    },
    [SET_ROOMID](context, payload) {
      console.log(payload);
      window.localStorage.setItem("roomid", payload.roomid);
      context.commit(SET_ROOMID, payload);
    },
    [SET_OFFLINE](context, payload) {
      context.commit(SET_OFFLINE, payload);
      if(payload.offline) {
        const offlineMessage = {
          isJoin: true,
          type: 'room',
          user: '本地用户',
          time: new Date(Date.now()).toLocaleString('zh-CN', {hour12: false})
        }
        setTimeout(() => {
          eventBus.$emit(LOG_TO_SCREEN, logParser(offlineMessage));  
        });
      }
    }
  },
  modules: {},
});